package com.abel.demo.config.security;

import com.abel.demo.domain.UserInfoDomain;
import com.abel.demo.model.SecAuthorityModel;
import com.abel.demo.model.SecRoleModel;
import com.abel.demo.model.UserInfoModel;
import com.abel.demo.services.UserInfoService;
import com.abel.demo.utils.BaseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: Abel.lin
 * Date: Created in 2018/7/13 14:49
 * Company: Abel.Studio
 * Copyright: Copyright (c) 2017
 * Description:
 */
@Service
public class UserSecurityService implements UserDetailsService {
    @Autowired
    private UserInfoService userInfoService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfoDomain userDomain = userInfoService.getUserDomainByUserName(username);
        if(userDomain == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList <>();
        List<SecAuthorityModel> authorities = userInfoService.selectAuthoritiesByUserName(username);
        if(!BaseUtil.isEmpty(authorities)){
            for(SecAuthorityModel authority : authorities){
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority.getCode());
                //1：此处将权限信息添加到 GrantedAuthority 对象中，在后面进行全权限验证时会使用GrantedAuthority 对象。
                grantedAuthorities.add(grantedAuthority);
            }
        }

        return new User(userDomain.getUserName(), userDomain.getPwd(), grantedAuthorities);
    }
}
